package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.WatchFaceStyleCustomAdapter;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.ble.BleService;
import com.jstyle.jclifexd.model.BleData;
import com.jstyle.jclifexd.utils.ImageUtils;
import com.jstyle.jclifexd.utils.PermissionsUtil;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.view.HeadCircleView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class WatchStyleCustomActivity extends BaseActivity implements WatchFaceStyleCustomAdapter.onItemClickListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_confirm)
    Button ivConfirm;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.recyclerView_watchStyle)
    RecyclerView recyclerViewWatchStyle;
    @BindView(R.id.iv_icon_usersetting)
    ImageView ivIconUsersetting;
    @BindView(R.id.iv_icon_text)
    ImageView ivIconText;
    @BindView(R.id.tv_userDefined)
    TextView tvUserDefined;
    private AlertDialog iconDialog;
    private Uri caremaUri;
    private Uri iconUri;
    private HeadCircleView circleView;
    static final int Request_SendPic=2900;
    private WatchFaceStyleCustomAdapter watchFaceStyleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watch_style_custom);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        writeData(SingleDealData.getDeviceInfo());
        iconUri = ImageUtils.getWatchIconUri();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);

        recyclerViewWatchStyle.setLayoutManager(gridLayoutManager);
         watchFaceStyleAdapter = new WatchFaceStyleCustomAdapter("");
        watchFaceStyleAdapter.setOnContactClickListener(this);
        recyclerViewWatchStyle.setAdapter(watchFaceStyleAdapter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onItemClick(int position) {
        if (position != 0) {
            writeData(SingleDealData.setWatchFaceCustomStyle(position));
            int id = getResources().getIdentifier("watch_style_text" + (position - 1), "drawable", getPackageName());
            ivIconText.setImageResource(id);
        } else {
            showChangeIconDialog();
        }
    }

    private void showChangeIconDialog() {
        if (iconDialog == null) {
            iconDialog = new AlertDialog.Builder(this, R.style.appalertdialog).setItems(R.array.change_icon, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 1) {
                        requestCameraAndStoragePermissions(PositionCamera);
                    } else {
                        requestCameraAndStoragePermissions(PositionPicture);

                    }
                }
            }).setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).create();
        }
        iconDialog.show();
        ScreenUtils.setDialogButtonTextColor(iconDialog);
    }

    private void requestCameraAndStoragePermissions(final int iconPosition) {
        PermissionsUtil.requestPermissions(this,
                new PermissionsUtil.PermissionListener() {
                    @Override
                    public void granted(String name) {
                        if (iconPosition == PositionCamera) {
                            caremaUri = ImageUtils.createImagePathUri(WatchStyleCustomActivity.this, "watch");
                            ImageUtils.openCameraImage(WatchStyleCustomActivity.this, caremaUri);
                        } else if (iconPosition == PositionPicture) {
                            ImageUtils.openLocalImage(WatchStyleCustomActivity.this);
                        }
                    }

                    @Override
                    public void NeverAskAgain() {

                    }

                    @Override
                    public void disallow(String name) {

                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
    }

    private static final String TAG = "WatchStyleCustomActivit";
    int PositionCamera = 0;
    int PositionPicture = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case Request_SendPic:
                ScreenUtils.showSetSuccessFul(ivConfirm,getString(R.string.send_pic_success));
                break;
            case ImageUtils.CROP_IMAGE:
                setHeadIcon();
                break;
            case ImageUtils.GET_IMAGE_BY_CAMERA:
                ImageUtils.cropImage(this, ivIconUsersetting.getWidth() * 2,
                        ivIconUsersetting.getHeight() * 2, caremaUri, iconUri);
                break;
            case ImageUtils.GET_IMAGE_FROM_PHONE:
                ImageUtils
                        .cropImage(this, ivIconUsersetting.getWidth() * 2,
                                ivIconUsersetting.getHeight() * 2, data.getData(),
                                iconUri);
                break;
            default:
                break;
        }
    }

    private void setHeadIcon() {
        // Log.i(TAG, "setHeadIcon: " + getFilesDir());
        iconUri = ImageUtils.getWatchIconUri();
        Bitmap bmHead = ImageUtils.findHeadBitmap(this, iconUri);
        circleView = new HeadCircleView(bmHead == null ? BitmapFactory.decodeResource(getResources(),
                R.drawable.user_icon) : bmHead);
        ivIconUsersetting.setImageDrawable(circleView);
    }


    @OnClick({R.id.iv_back, R.id.iv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_confirm:
                showSendPicDialog();
                break;
        }
    }

    long clickTime = 0;

    private void showSendPicDialog() {
        int watchStyle=watchFaceStyleAdapter.getSelectedPosition();
        if(watchStyle<1){
            ScreenUtils.showSetSuccessFul(tvUserDefined,getString(R.string.watch_style_notselected));
            return;
        }
        if (System.currentTimeMillis() - clickTime < 3000) return;
        clickTime = System.currentTimeMillis();
        File file = new File(ImageUtils.headPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        final File head = new File(file, "Watch");
        if(!head.exists()){
            ScreenUtils.showSetSuccessFul(ivConfirm,getString(R.string.select_pic_first));

            return;
        }
        Intent intent=new Intent(this,SendPicActivity.class);
        intent.putExtra( SendPicActivity.KEY_PIC_PATH, head.getAbsolutePath());
        startActivityForResult(intent,Request_SendPic);


    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState){
            case GET_DEVICE_INFO:
                String watchFaceStyle=maps.get(DeviceKey.KWatchFaceStyle);
                int style=Integer.valueOf(watchFaceStyle);
                watchFaceStyleAdapter.setSelectedPosition(style);
                if(style>64){
                    int id = getResources().getIdentifier("watch_style_text" + (style-65), "drawable", getPackageName());
                    ivIconText.setImageResource(id);
                }

                break;
        }
    }
}
